package ua.kpi_java_training.nikishov.module1;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * Class finds all palindromes in line
 * inputted with the keyboard and outputs them to the console.
 *
 * @author Alexey Nikishov
 */
public class Palindrome {
    public static final int MIN_PALINDROME_LENGTH = 3;
    public static ArrayList<String> palindromes = new ArrayList<String>();

    public static void main(String[] args) {
        String inputLine = input();
        findPalindromes(inputLine);
        output();
    }

    /**
     * Method finds all palindromes in entered string.
     */
    public static void findPalindromes(String inputLine){
        for(int lengthCurrentPal = MIN_PALINDROME_LENGTH; lengthCurrentPal <= inputLine.length(); lengthCurrentPal++) {
            findPalindromesSpecialLength(lengthCurrentPal, inputLine);
        }
    }

    /**
     * Method finds all palindromes specified length.
     *
     * @param lengthCurrentPal indicates the length of the required palindromes.
     */
    public static void findPalindromesSpecialLength(int lengthCurrentPal, String inputLine) {
        for(int beginSubstring = 0; beginSubstring + lengthCurrentPal <= inputLine.length(); beginSubstring++) {
            String tempString = inputLine.substring(beginSubstring, beginSubstring + lengthCurrentPal);
            if (isPalindrome(tempString)) {
                palindromes.add(tempString);
            }
        }
    }

    /**
     * Checks whether current word is a palindrome.
     *
     * @param  word word that is checked.
     * @return true if this word is a palindrome and false otherwise.
     */
    public static boolean isPalindrome(String word) {
       return word.equals(new StringBuffer(word).reverse().toString());
   }

    /**
     * Reads text longer than two characters from the console.
     */
   public static String input() {
       String inputLine = "";
       do {
            System.out.println("Input string (longer than two characters).");
            Scanner scan = new Scanner(System.in);
            inputLine = scan.nextLine();
       } while(inputLine.length() < MIN_PALINDROME_LENGTH );
       return inputLine;
   }

    /**
     * Outputs all found palindromes to console.
     */
   public static void output() {
        if (palindromes.isEmpty()) {
            System.out.println("Palindromes not found");
        } else {
            System.out.println("Found palindromes:");
            for (String pal : palindromes) {
                System.out.println(pal);
            }
        }
   }
}
